package startup

import (
	"context"
	"fmt"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/domain"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/event"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/svc"
	"gitee.com/unitedrhino/things/share/devices"
	"github.com/zeromicro/go-zero/core/logx"
)

func Init(svcCtx *svc.ServiceContext) {
	ProtocolInit(svcCtx)
}

func ProtocolInit(svcCtx *svc.ServiceContext) {
	err := svcCtx.Protocol.RegisterDeviceMsgDownHandler(func(ctx context.Context, info *devices.InnerPublish) error {
		err := event.NewDeviceDown(ctx, svcCtx).Handle(ctx, info)
		return err
	})
	logx.Must(err)
	err = svcCtx.Protocol.SubscribeDevMsg("+/+/+/post", func(ctx context.Context, topic string, payload []byte) error {
		err := event.NewDeviceUp(ctx, svcCtx).Handle(ctx, topic, payload)
		return err
	})
	logx.Must(err)
	err = svcCtx.Protocol.SubscribeDevMsg("/+/+/+/post", func(ctx context.Context, topic string, payload []byte) error {
		err := event.NewDeviceUp(ctx, svcCtx).Handle(ctx, topic, payload)
		return err
	})
	logx.Must(err)
	err = svcCtx.Protocol.SubscribeDevConn(func(ctx context.Context, info devices.DevConn) (devices.DevConn, error) {
		ci, err := domain.ParseClientID(info.ClientID)
		if err != nil {
			return info, err
		}
		info.DeviceName = ci.DeviceName
		pi := ci.ID
		if pi != "" {
			info.ClientID = fmt.Sprintf("%s&%s", pi, ci.DeviceName)
			info.ProductID = pi
		}
		return info, nil
	})
	logx.Must(err)
	err = svcCtx.Protocol.Start()
	logx.Must(err)
	svcCtx.Protocol.RunTimerHandles()
}
